#!/usr/local/bin/python2.5

_Copyright = "Copyright @ 2010 Michael P. Reilly. All rights reserved."

_SCM_ID = "$Id$"

from kcapp.app import logging, main
from kcapp.database import OSDBImage, OSDBLabels, OSDBUser
from kcapp.reqhandler import UserRequestHandler
from kcapp.tools import valid_name

class MainPage(UserRequestHandler):
    template_name = 'main'
    help_url = 'user'

class NewPage(UserRequestHandler):
    template_name = 'new_main'
    help_url = 'user_new'

class NewSubmissionPage(UserRequestHandler):
    template_name = 'new_submission'
    help_url = 'user_new'
    def process_request(self):
        agree = str(self.request.get('eula'))
        if agree != 'Iagree':
            self.send_msg('Must agree to End user license agreement')
            raise self.Redirect('/user/new')
        q = OSDBUser.all()
        q.filter('author =', self.user)
        if q.count() > 0:
            self.send_msg('User entry already exists')
            raise self.Redirect('/main')
        user = OSDBUser(author=self.user)
        user.put()
        raise self.Redirect('/main')


class LabelPage(UserRequestHandler):
    template_name = 'label_main'
    help_url = 'label'

    def process_request(self):
        q = OSDBLabels.all()
        q.filter('author =', self.user)
        self.vars['labelset'] = labels = []
        for result in q:
            labels.append( str(result.name) )

class LabelNewPage(UserRequestHandler):
    template_name = 'label_new'

class LabelNewSubmissionPage(UserRequestHandler):
    template_name = None
    def process_request(self):
        if self.request.get('submit') == 'Submit':
            lname = self.request.get('lname')
            if valid_name(lname):
                label = OSDBLabels(author=self.user, name=lname)
                label.put()
            else:
                self.send_msg('invalid label name', error=True)
        raise self.Redirect('/user/label')

class LabelEditPage(UserRequestHandler):
    template_name = 'label_edit'
    def process_request(self, lname):
        q = OSDBLabels.all()
        q.filter('author =', self.user)
        q.filter('name =', lname)
        if q.count() != 1:
            self.send_msg('label not longer exists', error=True)
            raise self.Redirect('/user/label')
        self.vars['lname'] = q.get().name

class LabelEditSubmissionPage(UserRequestHandler):
    template_name = None
    def process_request(self):
        req = str(self.request.get('submit'))
        lname = str(self.request.get('lname'))
        nlname = str(self.request.get('nlname'))
        if req == 'Remove':
            raise Self.Redirect('/user/label/remove/%s' % lname)
        elif req == 'Edit':
            q = OSDBLabels.all()
            q.filter('author =', self.user)
            q.filter('name =', lname)
            if q.count() != 1:
                self.send_msg('more than one label entry', error=True)
                raise self.Redirect('/user/label')
            label = q.get()
            dirty = False
            assert label.name == lname, 'Invalid data'
            if lname != nlname:
                if not valid_name(nlname):
                    self.send_msg('invalid label name', error=True)
                    raise self.Redirect('/user/label')
                label.name = nlname
                dirty = True
            if dirty:
                label.put()
            logging.warn('updated %s' % repr(lname))
        raise self.Redirect('/user/label')

class LabelRemovePage(UserRequestHandler):
    template_name = None
    def process_request(self, lname):
        q = OSDBLabels.all()
        q.filter('author =', self.user)
        q.filter('name =', lname)
        if q.count() != 1:
            self.send_msg('more than one label entry', error=True)
            raise self.Redirect('/user/label')
        label = q.get()
        q = SeedLabelMap.all()
        q.filter('label =', label)
        for entry in q:
            if entry.label == label:
                entry.delete()
        label.delete()
        logging.warn('removed %s' % repr(lname))
        self.Redirect('/user/label')

class SecIconPage(UserRequestHandler):
    template_name = 'secicon_main'
    help_url = 'security/icon'
    def process_request(self):
        user = self.retrieve_user()
        self.vars['upload_url'] = '/user/secicon/set'
        if user.pswd and user.pswd.itype:
            # not implimented
            self.vars['secicon'] = '/images/secicon/nosecicon.png'
        elif user.pswd:
            self.vars['secicon'] = '/images/secicon/%s.png' % user.pswd.iname
        else:
            self.vars['secicon'] = '/images/secicon/nosecicon.png'
        self.vars['iuser'] = user
        self.vars['stock'] = []
        for stock in ('stock00', 'stock01', 'stock02', 'stock03',
                      'stock04', 'stock05', 'stock06', 'stock07'):
            if user.pswd and \
               (not user.pswd.itype and user.pswd.iname == stock):
                self.vars['stock'].append( (stock, 'checked') )
            else:
                self.vars['stock'].append( (stock, '') )

class SecIconSetPage(UserRequestHandler):
    template_name = None
    def process_request(self):
        from kcapp.database import StockMd5s
        req = str(self.request.get('submit'))
        itype = str(self.request.get('itype')) == 'true'
        iname = str(self.request.get('iname'))
        if req == 'Cancel':
            raise self.Redirect('/user')
        user = self.retrieve_user()
        if itype or (not itype and not iname):
            self.send_msg('Must supply a filename or select a stock image', error=True)
            raise self.Redirect('/user/secicon')
        if iname:
            logging.warn('OSDBImage(%s, %s, %s)' % (repr(user.author), repr(itype), repr(iname)))
            q = StockMd5s.all()
            q.filter('iname =', iname)
            e = q.get()
            pswd = OSDBImage(author=user.author, itype=itype, iname=iname, md5=e.md5)
            pswd.put()
            if user.pswd:
                user.pswd.delete()
                user.pswd = None
            user.pswd = pswd
            user.put()
            logging.warn("updated secicon for %s" % self.user.nickname())
            self.send_msg('secicon updated')
        raise self.Redirect('/user')

class SecurityPage(UserRequestHandler):
    template_name = 'secquest_main'
    help_url = 'security/question'
    def process_request(self):
        user = self.retrieve_user()
        self.vars['secq'] = user.securityQuestion or ''
        self.vars['seca'] = user.securityAnswer or ''

class SecurityVerifyPage(UserRequestHandler):
    template_name = None
    def process_request(self):
        req = str(self.request.get('submit'))
        secq = str(self.request.get('secq'))
        seca = str(self.request.get('seca'))
        if req == 'Cancel':
            raise self.Redirect('/user')
        if secq == '' or seca == '':
            raise self.Redirect('/user/security')
        user = self.retrieve_user()
        user.securityQuestion = secq
        user.securityAnswer = seca
        user.put()
        logging.warn("update security q's for %s" % self.user.nickname())
        raise self.Redirect('/user')

URL_Map = [
  ('/user', MainPage),
  ('/user/new', NewPage),
  ('/user/new/submit', NewSubmissionPage),
  ('/user/label', LabelPage),
  ('/user/label/new', LabelNewPage),
  ('/user/label/new/submission', LabelNewSubmissionPage),
  ('/user/label/edit/submission', LabelEditSubmissionPage),
  ('/user/label/edit/(.*)', LabelEditPage),
  ('/user/label/remove/(.*)', LabelRemovePage),
  ('/user/secicon', SecIconPage),
  ('/user/secicon/set', SecIconSetPage),
  ('/user/security', SecurityPage),
  ('/user/security/verify', SecurityVerifyPage),
]

if __name__ == "__main__":
    main(URL_Map)

